import axios from 'axios'
import store from '../store';
import router from '@/router';

//创建实例
const server = axios.create({
  baseURL: "http://localhost:8888/api",
  // baseURL: "http://110.41.83.104/api",
  timeout: 30000,
  header: {
    'Content-Type': 'application/json'
  }
})

//请求拦截
// 添加请求拦截器，在请求头中加token
server.interceptors.request.use(
  (config) => {
    //本地存储token
    if (store.state.token != null) {
      config.headers.satoken = store.state.token;
    }

    //Vuex管理
    // const token = store.state.user.token;
    // token && (config.headers.Authorization = token);
    return config;
  },
  (err) => {

    Promise.reject(err);
  }
)

//响应拦截
server.interceptors.response.use(
  (res) => {
    var code = res.data.code;
    if (code == 401) {
      router.push('/login');
    }

    return res;
  },
  (err) => {
    Promise.reject(err);
  }
)

export default server;